package com.tsfyun.scm.controller.support;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.tsfyun.common.base.constant.LimitConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.concurrent.TimeUnit;

/**
 *   验证码的生成
 */
@RefreshScope
@RestController
@Slf4j
@RequestMapping("/kaptcha")
public class KaptchaController {

    /**
     * 1、验证码工具
     */
    @Autowired
    private DefaultKaptcha kaptcha;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${frequency.exipre:60}")
    private Integer frequencyExpireTime;

    /**
     * 生成验证码
     * @throws Exception
     */
    @RequestMapping("/limit")
    public void getKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
            throws Exception {
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        String limitRequestId = httpServletRequest.getParameter("limitRequestId");
        String rightCode = kaptcha.createText();
        BufferedImage challenge = kaptcha.createImage(rightCode);
        ImageIO.write(challenge, "jpg", jpegOutputStream);
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream =
                httpServletResponse.getOutputStream();
        responseOutputStream.write(jpegOutputStream.toByteArray());
        redisTemplate.opsForValue().set(LimitConstant.FREQUENCY_VALIDATE_CODE + limitRequestId, rightCode,
                frequencyExpireTime, TimeUnit.SECONDS);
        responseOutputStream.flush();
        responseOutputStream.close();

    }

}

